import { checkType, randomNum } from "../shared/utils";

//*,任意字符出现一次到多次 非贪婪模式
const reg_onclick = /onClick="(.+?)"/g;
const reg_fnName = /^(.+?)\(/i;
//changeName('苏普路')
const reg_args = /\((.*?)\)/;
let eventPool = [];
/**
 * eventPool = []
 * {
 *  mark:new Date().getTime() + Math.random() * 10000
 *  handler:事件处理函数的字符串
 *  type:'click'
 * }
 */

export function eventFormat(template) {
    return template.replace(reg_onclick, function (node, key) {
        const _mark = randomNum();
        eventPool.push({
            mark: _mark,
            handler: key.trim(),
            type: 'click'
        })
        return `data-mark="${_mark}"`;
    });
}

export function bindEvent(methods) {
    const oAllElements = document.querySelectorAll('*');
    let itemElem = null;
    eventPool.forEach((event) => {
        for (var i = 0; i < oAllElements.length; i++) {
            itemElem = oAllElements[i]
            if (parseInt(itemElem.getAttribute('data-mark')) === event.mark) {
                itemElem.addEventListener(event.type, function (e) {
                    let fnName = event.handler.match(reg_fnName)[1];
                    let arg = checkType(event.handler.match(reg_args)[1]);
                    methods[fnName](arg);
                }, false);
            }
        }
    })
}